import { createAnimate } from "./animate.js";

let titles = document.querySelectorAll(".menu h2");
let itemHeight = 30;
let totalMS = 1500;

for (let i = 0; i < titles.length; i++) {
    titles[i].onclick = function () {
        let beforeOpened = document.querySelector(".subMenu-container[status=opened]");
        let playingSubmenu = document.querySelector('.subMenu-container[status=playing]');
        if (playingSubmenu) {
            return;
        }
        if (beforeOpened) {
            closeSubmenu(beforeOpened);
        }
        toggleSubmenu(this.nextElementSibling);
    }
}

function openSubmenu(submenu) {
    let status = submenu.getAttribute('status');
    if (status && status !== 'closed') return;
    let from = 0;
    let to = itemHeight * submenu.children.length;
    submenu.setAttribute('status', 'playing')
    createAnimate({
        from,
        to,
        totalMS,
        onMove: function (n) {
            submenu.style.height = n + 'px';
        },
        onEnd() {
            submenu.setAttribute('status', 'opened')
        }
    })
}

function closeSubmenu(submenu) {
    let status = submenu.getAttribute('status');
    if (status !== 'opened') return;
    let from = itemHeight * submenu.children.length;
    let to = 0;
    submenu.setAttribute('status', 'playing')
    createAnimate({
        from,
        to,
        totalMS,
        onMove: function (n) {
            submenu.style.height = n + 'px';
        },
        onEnd() {
            submenu.setAttribute('status', 'closed')
        }
    })
}

function toggleSubmenu(subMenu) {
    let status = subMenu.getAttribute('status');
    if (status === 'playing') {
        return;
    } else if (status === 'opened') {
        closeSubmenu(subMenu);
    } else {
        openSubmenu(subMenu);
    }
}